var alarms = [];
var table;
var undefinedReplace = '空';
var currentTime = $('#time').val();
var start = $('#startTime').val();
var end = $('#endTime').val();
var stationId = $('#stationId').val();
var columns = [ '序号', '告警时间', '电压', '变电站', '线路', '保护', '告警内容', '中断时长', '主保护闭锁',
		'后备保护闭锁', '重合闸闭锁' ];
var initColumns = [ '序号', '告警时间', '电压', '变电站', '线路', '保护', '告警内容', '中断时长' ];
var linesLength = 0;
var stationsLength = 0;
var voltagesLength = 2;
function init() {
	$('#start').val($('#startTime').val());
	$('#end').val($('#endTime').val());
	$('#stationId').val($('#stationId').val());
	$('#start').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	$('#end').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		pickerPosition : 'bottom-left',
		todayHighlight : true
	});
	loadColumnsFilter(initColumns);
	loadData();
}
function loadData() {
	$.getJSON("/rest/protectAlarm/getProtectDeviceAlarmByTime/" + currentTime,
			function(result) {
				alarms = result;
				alarms.sort(sortAlarms);
				$('#selectButton').removeClass('hasSelected');
				loadFilter(stationId);
				var filterAlarms = [];
				if (stationId) {
					for ( var i in alarms) {
						if (alarms[i].stationId == stationId) {
							filterAlarms.push(alarms[i]);
						}
					}
					$('#selectButton').addClass('hasSelected');
					loadContent(filterAlarms);
				} else {
					loadContent(alarms);
				}
				stationId = undefined;
			});
}
function sortAlarms(obj1, obj2) {
	// 主要按照lastAlarmTime排序，次要按照eventStart排序
	var t1 = obj1.lastAlarmTime ? obj1.lastAlarmTime : 0;
	t1 = t1.time ? t1.time : t1;
	var t2 = obj2.lastAlarmTime ? obj2.lastAlarmTime : 0;
	t2 = t2.time ? t2.time : t2;
	return t2 - t1;
}
function query() {
	var s = $('#start').val();
	var e = $('#end').val();
	if (s == start && e == end) {
		doFilter();
	} else {
		start = s;
		end = e;
		loadData();
	}
}
function loadFilter(stationId) {
	var lines = [];
	var lineMap = {};
	var stations = [];
	var stationMap = {};
	var stationName;
	// time countT maxTime
	for ( var i in alarms) {
		var a = alarms[i];
		if (stationId && !stationName) {
			if (a.stationId == stationId) {
				stationName = a.stationName;
			}
		}

		var line = a.lineName ? a.lineName : undefinedReplace;
		var station = a.stationName ? a.stationName : undefinedReplace;
		var voltage = a.voltage ? a.voltage : undefinedReplace;
		if (lines.indexOf(line) == -1) {
			lines.push(line);
		}
		if (stations.indexOf(station) == -1) {
			stations.push(station);
		}
		// 加title
		var l = lineMap[line];
		if (!l) {
			l = {
				countNT : 0,
				timeAll : 0,
				countAll : 0,
				notReturnCount : 0
			};
			lineMap[line] = l;
		}
		refreshItem(a, l);

		var s = stationMap[station];
		if (!s) {
			s = {
				countNT : 0,
				timeAll : 0,
				countAll : 0,
				notReturnCount : 0
			};
			stationMap[station] = s;
		}
		refreshItem(a, s);
	}
	// 先按照count排，count相同按照总时长
	lines.sort(sortLines);
	stations.sort(sortStation);
	linesLength = lines.length;
	stationsLength = stations.length;
	$('#lines')
			.html(getCheckBox(lines, 'lines', 'doFilter();', lineMap, lines));
	$('#stations').html(
			getCheckBox(stations, 'stations', 'doFilter();', stationMap,
					stationName ? [ stationName ] : stations));
	selectAllVoltages();
	function refreshItem(alarm, item) {
		if (!alarm.channelAlarms || alarm.channelAlarms.length == 0) {
			item.countNT++;
		}
		item.countAll++;
		item.timeAll += alarm.durationTime;
		if (alarm.durationTime == 0) {
			item.notReturnCount++;
		}
	}
	function selectAllVoltages() {
		var ss = document.getElementsByName("voltages");
		var ssAll = document.getElementById("voltagesAll");
		ssAll.checked = true;
		for ( var i in ss) {
			ss[i].checked = true;
		}
	}
	function sortLines(line1, line2) {
		var t1 = line1 == undefinedReplace ? 0 : 1;
		var t2 = line2 == undefinedReplace ? 0 : 1;
		if (t2 + t1 < 2) {
			return t2 - t1;
		}
		var m1 = lineMap[line1];
		var m2 = lineMap[line2];
		if (m1.countNT == m2.countNT) {
			var averageTime1 = m1.timeAll / (m1.countAll - m1.notReturnCount);
			var averageTime2 = m1.timeAll / (m1.countAll - m1.notReturnCount);
			return averageTime2 - averageTime1;
		} else {
			return m2.countNT - m1.countNT;
		}
	}
	function sortStation(station1, station2) {
		var t1 = station1 == undefinedReplace ? 0 : 1;
		var t2 = station2 == undefinedReplace ? 0 : 1;
		if (t2 + t1 < 2) {
			return t2 - t1;
		}
		var m1 = stationMap[station1];
		var m2 = stationMap[station2];
		if (m1.countNT == m2.countNT) {
			var averageTime1 = m1.timeAll / (m1.countAll - m1.notReturnCount);
			var averageTime2 = m1.timeAll / (m1.countAll - m1.notReturnCount);
			return averageTime2 - averageTime1;
		} else {
			return m2.countNT - m1.countNT;
		}
	}
}
function loadColumnsFilter(selectColumns) {
	if (!selectColumns) {
		selectColumns = columns;
	}
	$('#columns').html(
			getCheckBox(columns, 'columns', 'doColumnFilter();', null,
					selectColumns));
}
function doFilter() {
	var lines = getCheckBoxValue('lines');
	var voltages = getCheckBoxValue('voltages');
	var stations = getCheckBoxValue('stations');
	changeSelectButtonStatus(lines, voltages, stations);
	var filterAlarms = [];
	for ( var i in alarms) {
		var a = alarms[i];
		var line = a.lineName ? a.lineName : undefinedReplace;
		var voltage = a.voltage ? a.voltage : undefinedReplace;
		var station = a.stationName ? a.stationName : undefinedReplace;
		if (lines.indexOf(line) > -1 && voltages.indexOf(voltage) > -1
				&& stations.indexOf(station) > -1) {
			filterAlarms.push(a);
		}
	}
	loadContent(filterAlarms);
}
function changeSelectButtonStatus(lines, voltages, stations) {
	if (lines.length == linesLength && stations.length == stationsLength
			&& voltages.length == voltagesLength) {
		$('#selectButton').removeClass('hasSelected');
	} else {
		$('#selectButton').addClass('hasSelected');
	}
}
function changeColumnsSelectButtonStatus(length) {
	if (columns.length == length) {
		$('#columnsSelectButton').removeClass('hasSelected');
	} else {
		$('#columnsSelectButton').addClass('hasSelected');
	}
}
function getCheckBoxValue(name) {
	var obj = document.getElementsByName(name);
	var s = [];
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			s.push(obj[i].value);
		}
	}
	return s;
}
function getCheckBox(data, name, func, map, selects) {
	var c = '';
	for ( var i in data) {
		if (map) {
			var item = map[data[i]];
			var countNT = item.countNT;
			var averageTime = (item.timeAll / (item.countAll - item.notReturnCount))
					.toFixed(2);
			var color = item.notReturnCount ? 'red' : 'black';
			var notReturn = item.notReturnCount ? ',未复归' + item.notReturnCount
					+ '次' : '';
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label style="color:' + color + '" title="非通道引起中断' + countNT
					+ '次,平均中断时长' + averageTime + 'ms' + notReturn
					+ '"><input name="' + name + '" type="checkbox" onchange="'
					+ func + '" ' + checked + ' value="' + data[i] + '" />'
					+ data[i] + '</label>';
		} else {
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label><input name="' + name + '" type="checkbox" onchange="'
					+ func + '" ' + checked + ' value="' + data[i] + '" />'
					+ data[i] + '</label>';
		}

	}
	return c;
}
function loadContent(alarms) {
	loadTable(alarms);
	refreshAllSelectAllButtonStatus();
}
function loadTable(alarms) {
	if (table) {
		table.getTable().destroy();
	}
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = false;
	var defs = [ {
		targets : 0,
		width : '5%'
	}, {
		targets : 1,
		width : '15%'
	}, {
		targets : 2,
		width : '5%'
	}, {
		targets : 3,
		width : '10%'
	}, {
		targets : 4,
		width : '10%'
	}, {
		targets : 5,
		width : '25%'
	}, {
		targets : 6,
		width : '15%'
	}, {
		targets : 7,
		width : '10%'
	}, {
		targets : 8,
		width : '21%'
	} ];
	opt.scrollY = "490px";
	var datas = [];
	for ( var i in alarms) {
		var f = alarms[i];
		var durationTime = f.durationTime;
		var title = '';
		if (durationTime) {
			title = 'title="' + (durationTime / 60000).toFixed(2) + '分钟"';
			durationTime = durationTime + 'ms';
		} else {
			durationTime = '未复归';
		}
		durationTime = '<span ' + title + ' style="color:red;">' + durationTime
				+ '</span>';
		datas.push([ Number(i) + 1, time(f.eventStart) + '.' + f.mStartMs,
				str(f.voltage), str(f.stationName), str(f.lineName),
				str(f.protectType), str(f.alarmMsg), durationTime,
				boo(f.firstlock), boo(f.secondlock), boo(f.thirdlock) ]);
	}
	// 筛选列
	var eles = document.getElementsByName('columns');
	var targets = [];
	for (var i = 0; i < eles.length; i++) {
		if (!eles[i].checked) {
			targets.push(i);
		}
	}
	defs.push({
		visible : false,
		targets : targets
	});
	opt.columnDefs = defs;
	table = new MyTable("alarmTable", columns, opt);
	table.setDataSet(datas).show();
}
function selectAll(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doFilter();
}
function selectAllColumns(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doColumnFilter();
}
function doColumnFilter() {
	var eles = document.getElementsByName("columns");
	var length = 0;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		var col = table.getTable().column(i);
		col.visible(show);
		if (show) {
			length++;
		}
	}
	changeColumnsSelectButtonStatus(length);
	redrawTable();
}
function redrawTable() {
	if (table) {
		table.getTable().draw();
	}
	// $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
}
function str(v) {
	return v ? v : '';
}
function time(v) {
	if (!v) {
		return '';
	} else {
		return new Date(v.time ? v.time : v).toLocaleString();
	}
}
function refreshAllSelectAllButtonStatus() {
	var ids = [ 'columns', 'stations', 'lines', 'voltages' ];
	for ( var i in ids) {
		refreshSelectAllButtonStatus(ids[i]);
	}
}
function refreshSelectAllButtonStatus(id) {
	var eles = document.getElementsByName(id);
	var all = document.getElementById(id + 'All');
	var checked = true;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		if (!show) {
			checked = false;
			break;
		}
	}
	all.checked = checked;
}
function boo(v) {
	return v ? '√' : '×';
}

function resizeHtml() {
	if (table) {
		table.getTable().draw();
	}
}